package com.zzty.zzlp.controller;

import com.zzty.zzlp.commom.FileUpload;
import com.zzty.zzlp.entity.Twitter;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.service.TwitterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/Publish")
public class PublishController {
    @Autowired
    TwitterService twitterService;

    @RequestMapping(value = "saysay", method = RequestMethod.POST)
    @ResponseBody
    public void upload(@RequestParam(value = "files") MultipartFile[] files,
                       @RequestParam(value = "id") String id,
                       HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String dateTime = df.format(new Date());// new Date()为获取当前系统时间
//        System.out.println(user.getId());
        System.out.println(id);
        String imgName = "";
        if (files != null) {
            for (MultipartFile file : files) {
                System.out.println(file.getOriginalFilename());
                Map<String, String> fileInfo = FileUpload.uploadFile(file, "img");
                if ("".equals(imgName)) {
                    imgName = fileInfo.get("filename");
                } else {
                    imgName = imgName + "|" + fileInfo.get("filename");
                }
            }
        }
        Twitter twitter = new Twitter();
        twitter.setAuthor(user.getId());
        twitter.setContent(id);
        twitter.setImg(imgName);
        twitter.setTime(dateTime);
        twitterService.publishTwitter(twitter);
    }
}
